/**
 * 设置权限
 * 
 * admin/set/role
 */

const User_info = require('../../../models/usersInfo')
const Users = require('../../../models/users')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')
const MySQLManager = require('../../../utils/MySQLManager');
const sequelize = MySQLManager


const set_role = async function (req, res) {
    try {
        if (req.body.user_role){
            if (!['0','1','2'].includes(req.body.user_role)) {
                $.sendMessage(res, 1015, '参数user_role为有效代码')
                return
            }
        }
        
        if (!req.body.id) {
            $.sendMessage(res, 1015, '参数id缺少啊兄弟')
            return
        }

        var user_name = await User_info.findOne({
            where: {
                id: req.body.id
            },
            attributes: ['user_name', 'user_role']
        })

        if (user_name == null) {
            $.sendMessage(res, 1015, '无效id')
            return
        }
        
        if (user_name.dataValues.user_role == 'student') {
            $.sendMessage(res, 1015, '学生现在还不能拥有别的权限')
            return
        }

         // 事务
        return sequelize.transaction(function (t) {
            return Users.update(
            {
                user_role: $.getUserRoleByCode(req.body.user_role) + ''
            },
            {
                where: {
                    user_name: user_name.dataValues.user_name + ''
                }
            }
            , 
            {transaction: t}).then(function (user) {
            return User_info.update(
                {
                    user_role: $.getUserRoleByCode(req.body.user_role) + ''
                },
                {
                    where: {
                        user_name: user_name.dataValues.user_name + ''
                    }
                }
                , {transaction: t})
            })
        
        })
        // 请求完整完成
        .then(function (result) {
            res.json({
                code: 200,
                message: '修改状态成功',
                result: result
            })
         
            utils.create_a_log(req, '权限管理', '角色修改')
            return
        })
        // 处理sequalize异常
        .catch(function (err) {
            res.json({
                code: 1017,
                message: '修改状态失败',
                err: 'error' + err
            })
            
        });
    }

    catch(err) {
        $.sendMessage(res, 0000, 'err' + err)
        return
    }
    
}
    
module.exports = set_role